package com.recharge.web.controller;


import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.common.util.Constant;
import com.recharge.common.util.ExcelUtil;
import com.recharge.common.util.TemplateUtils;
import com.recharge.domain.query.DepositQueryDO;
import com.recharge.domain.vo.DepositDO;
import com.recharge.service.DepositService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 存款单表 前端控制器
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@RestController
@RequestMapping("/deposit")
public class DepositController extends BaseController{
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Value("${file.deposit.template}")
    private String fileTemplatePath;

    @Autowired
    DepositService depositService;

//    @Deprecated
//    @RequiresPermissions("deposit:getIds")
//    @RequestMapping(value="/getIds.html", method = RequestMethod.POST)
//    @ApiOperation(value = "查询多个存款详细信息")
//    public @ResponseBody
//    ObjectResponse getIds(@RequestBody DepositQueryDO domain) {
//        ObjectResponse response = new ObjectResponse();
//
//        if (TemplateUtils.isEmpty(domain.getId())){
//            response.setStatus(ErrorCode.SYSTEM_EXCEPTION.getCode());
//            response.setMsg(ErrorCode.SYSTEM_EXCEPTION.getMsg());
//            logger.debug("没有商户ID");
//            return response;
//        }
//
//        ResultDO result = depositService.getIds(domain.getId());
//
//        if (result.isSuccess()) {
//            response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
//        } else {
//            response.setStatus(result.getErrorCode().getCode());
//            response.setMsg(result.getErrorCode().getMsg());
//        }
//        return response;
//    }
//
//    @Deprecated
//    @RequiresPermissions("deposit:getAudit")
//    @RequestMapping(value="/getAudit.html", method = RequestMethod.POST)
//    @ApiOperation(value = "查询待审核记录")
//    public @ResponseBody
//    ObjectResponse getAudit(@RequestBody DepositQueryDO domain) {
//        ObjectResponse response = new ObjectResponse();
////        domain.setIsFinish(0);
//        domain.setStatus(0);
//
//        ResultDO result = depositService.findList(domain);
//        if (result.isSuccess()) {
//            response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
//        } else {
//            response.setStatus(result.getErrorCode().getCode());
//            response.setMsg(result.getErrorCode().getMsg());
//        }
//        return response;
//    }

    @RequiresPermissions("deposit:getRecord")
    @RequestMapping(value="/getRecord.html", method = RequestMethod.POST)
    @ApiOperation(value = "查询渠道商信用款记录")
    public @ResponseBody
    ObjectResponse getRecord(@RequestBody DepositQueryDO domain) {
        ObjectResponse response = new ObjectResponse();

        if (domain.getMerchantId() == null){
            response.setStatus(ErrorCode.SYSTEM_EXCEPTION.getCode());
            response.setMsg(ErrorCode.SYSTEM_EXCEPTION.getMsg());
            logger.debug("没有渠道商ID");
            return response;
        }

        domain.setStatus(1);
//        domain.setIsFinish(0);
        domain.setType(Constant.DEPOSIT_TYPE_CREDIT);

        ResultDO result = depositService.findList(domain);
        if (result.isSuccess()) {
            response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("deposit:page")
    @RequestMapping(value="/page.html", method = RequestMethod.POST)
    @ApiOperation(value = "查询存款记录")
    public @ResponseBody
    ObjectResponse page(@RequestBody DepositQueryDO domain) {
        ObjectResponse response = new ObjectResponse();

        ResultDO result = depositService.findList(domain);
        if (result.isSuccess()) {
            response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("deposit:apply")
    @PostMapping(value = "/apply.html")
    @ApiOperation(value = "申请加款")
    public @ResponseBody
    ObjectResponse apply(@RequestBody DepositDO domain){
        ObjectResponse response = new ObjectResponse();

        // 表单验证
        boolean verification = domain.verification();
        if (!verification){
            response.setMsg(ErrorCode.PARAM_VERIFICATION_ERROR.getMsg());
            response.setStatus(ErrorCode.PARAM_VERIFICATION_ERROR.getCode());
            return response;
        }

        ResultDO result = depositService.applyDeposit(domain, getUserName());
        if (result.isSuccess()) {
            response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("deposit:verify")
    @PostMapping(value = "/verify.html")
    @ApiOperation(value = "审核加款申请")
    public @ResponseBody
    ObjectResponse verify(@RequestBody DepositDO domain){
        ObjectResponse response = new ObjectResponse();
        /*
           参数校验
         */
        response.setStatus(ErrorCode.PARAM_GET_ERROR.getCode());
        response.setMsg(ErrorCode.PARAM_GET_ERROR.getMsg());
        if (domain.getId() == null || domain.getStatus() == null){
            return response;
        }else if (domain.getStatus() != Constant.DEPOSIT_VERIFICATION_SUCCESS
                && domain.getStatus() != Constant.DEPOSIT_VERIFICATION_FAIL){
            return response;
        }
        /*
            加款审核
         */
        ResultDO result = depositService.verifyDeposit(domain, getUserName());
        if (result.isSuccess()) {
            response.setStatus(ErrorCode.SYSTEM_SUCCESS.getCode());
            response.setMsg(ErrorCode.SYSTEM_SUCCESS.getMsg());
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("deposit:excel-download")
    @RequestMapping(value = "/excelDownload.html" ,method = RequestMethod.POST)
    @ApiOperation(value = "excel文件导出加款记录",notes = "")
    public void excelDownload(@RequestBody DepositQueryDO query, HttpServletResponse response) {

        String[] types = {"未知","预付款","临时授信","保证金","固定授信"};
        String[] statuses = {"待审核","通过","驳回"};
        ResultDO result = depositService.findList(query);
        PageDO<DepositDO> lists = (PageDO<DepositDO>)result.getModel(ResultDO.FIRST_MODEL_KEY);
        List<DepositDO> list = lists.getData();
//        List<DepositDO> list= (List<DepositDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
        List<Object> downloadList = new ArrayList<>();
        list.forEach(item -> {
            Map<String,Object> data = new HashMap<>();
            data.put("a1", item.getDepositNo());
            data.put("a2", item.getMerchantName());
            data.put("a3", item.getAmount()/1000);
            data.put("a4", (!TemplateUtils.isEmpty(item.getReturnAmount())) ? item.getReturnAmount()/1000 : "");
            data.put("a5", item.getConfirmAmount()/1000);
            data.put("a6", item.getApplicant());
            data.put("a7", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item.getApplicantDate()));
            data.put("a8", item.getChecker());
            data.put("a9", types[item.getType()]);
            data.put("a10", statuses[item.getStatus()]);
            data.put("a11", (!TemplateUtils.isEmpty(item.getBeforeBalance())) ? item.getBeforeBalance()/1000 : "");
            data.put("a12", (!TemplateUtils.isEmpty(item.getAfterBalance())) ? item.getAfterBalance()/1000 : "");
            downloadList.add(data);
        });
        ExcelUtil.exportExcel(response, downloadList, fileTemplatePath, "加款记录列表.xls");
    }

//    @RequiresPermissions("deposit:close")
//    @PostMapping(value = "/close.html")
//    @ApiOperation(value = "关闭长期授信")
//    public @ResponseBody
//    ObjectResponse closeCredit(@RequestBody DepositDO domain){
//        ObjectResponse response = new ObjectResponse();
//        /*
//           参数校验
//         */
//        if (domain.getMerchantId() == null){
//            response.setStatus(ErrorCode.PARAM_GET_ERROR.getCode());
//            response.setMsg(ErrorCode.PARAM_GET_ERROR.getMsg());
//            return response;
//        }
//        /*
//            关闭长期授信
//         */
//        ResultDO result = depositService.closeCredit(domain);
//        if (result.isSuccess()) {
//            response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
//        } else {
//            response.setStatus(result.getErrorCode().getCode());
//            response.setMsg(result.getErrorCode().getMsg());
//        }
//        return response;
//    }

}
